package com.hq.tdxt.actions;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.eredlab.g4.arm.util.ArmConstants;
import org.eredlab.g4.arm.util.idgenerator.IDHelper;
import org.eredlab.g4.ccl.datastructure.Dto;
import org.eredlab.g4.ccl.datastructure.impl.BaseDto;
import org.eredlab.g4.ccl.json.JsonHelper;
import org.eredlab.g4.ccl.util.G4Utils;
import org.eredlab.g4.demo.service.DemoService;
import org.eredlab.g4.rif.web.BaseAction;
import org.eredlab.g4.rif.web.CommonActionForm;

import com.hq.tdxt.service.TdxtService;

public class TdxtAction extends  BaseAction{
	//private static final String type1="合同价款附件";
	//private static final String type2="处置方案附件";
	private TdxtService tdxtService = (TdxtService) getService("tdxtService");
	public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		System.out.println("提示：你一进入土地管理模块。。。。。。。。");
		return mapping.findForward("indexView");
	}
	public ActionForward queryByParam(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		System.out.println("提示：正在查询土地信息。。。。。。。。");
		CommonActionForm aForm = (CommonActionForm) form;
		Dto dto = aForm.getParamAsDto(request);
		List list = g4Reader.queryForPage("Land.queryByParam", dto);
		System.out.println(list);
		Integer countInteger = (Integer) g4Reader.queryForObject("Land.queryByParamCount", dto);
		String jsonString = JsonHelper.encodeList2PageJson(list, countInteger,null);
		super.write(jsonString, response);
		return mapping.findForward(null);
	}
	public synchronized ActionForward updateLand(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		System.out.println("提示：正在修改土地表中的信息。。。。。。。");
		CommonActionForm cForm = (CommonActionForm) form;
		Dto inDto = cForm.getParamAsDto(request);
		System.out.println("提示：被修改的编号是"+inDto.getAsString("land_sn"));
		inDto.put("LAND_SN",inDto.getAsString("land_sn"));
		inDto.put("land_tran_year",inDto.getAsInteger("land_tran_year"));
		inDto.put("land_area",inDto.getAsBigDecimal("land_area"));
		//更新一次！
		inDto=this.uploadFile(cForm, inDto);
		//将对数据保存的逻辑处理放在服务层去，直接调用里面的方法就可以了！
		tdxtService.updateLand(inDto);
		setOkTipMsg("数据修改成功", response);
		return mapping.findForward(null);
	}
	public ActionForward deleteLand(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		System.out.println("提示：正在删除土地表中信息。。。。。。。");
		CommonActionForm aForm = (CommonActionForm) form;
		Dto inDto = aForm.getParamAsDto(request);
		System.out.println("提示：被删除的编号是"+inDto.getAsString("land_sn"));
		tdxtService.deleteLand(inDto);
		setOkTipMsg("土地信息删除成功", response);
		return mapping.findForward(null);
	}
	//一次删除多条记录
	public ActionForward deleteLands(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		System.out.println("提示：正在删除多条土地表中信息。。。。。。。");
		CommonActionForm aForm = (CommonActionForm) form;
		Dto dto = aForm.getParamAsDto(request);
		String[] strChecked = dto.getAsString("strChecked").split(",");
		Dto delete=new BaseDto();
		//循环覆盖，虚幻删除！
		for (int i = 0; i < strChecked.length; i++) 
		{
			delete.put("land_sn",strChecked[i]);
			tdxtService.deleteLand(delete);
		}
		setOkTipMsg("多条文件删除成功", response);
		return mapping.findForward(null);
	}
	public synchronized ActionForward addLand(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		System.out.println("提示：正在添加土地表中信息。。。。。。。");
		CommonActionForm aForm = (CommonActionForm) form;
		Dto inDto = aForm.getParamAsDto(request);
		//参数一个项目编号！由于后面文件的保存都需要用到这个参数，因此在保存文件之前就设置编号值！
		String xmid=IDHelper.getXmID();
		inDto.put("LAND_SN",xmid);
		inDto=this.uploadFile(aForm, inDto);
		tdxtService.addLand(inDto);
		setOkTipMsg("土地信息添加成功", response);
		return mapping.findForward(null);
	}
	//只要为了添加附件路径键值对！
	private Dto uploadFile(CommonActionForm form,Dto beforedto)
	{
		FormFile file1=form.getFile1();
		FormFile file2=form.getFile2(); 
		//避免上传同名的文件保存二次！
		if(file1.getFileName().trim().equals(file2.getFileName().trim()))
		{
			System.out.println("提示：由于二个文件相同因此只保存一个。。。。。");
			String path=this.saveFile(file1, beforedto,null);
			System.out.println("---------------------------"+path);
			//填充保存路径！
			beforedto.put("LAND_AGR",path);
			beforedto.put("LAND_DEAL_SCH",path);
		}
		else
		{
			System.out.println("提示：由于二个文件不相同因此保存二个文件。。。。。");
			String arg=this.saveFile(file1, beforedto,null);
			String sch=this.saveFile(file2, beforedto,null);
			System.out.println("---------------------------"+arg);
			System.out.println("---------------------------"+sch);
			//填充保存路径！
			beforedto.put("LAND_AGR",arg);
			beforedto.put("LAND_DEAL_SCH",sch);
		}
		//将处理之后的dto返回！
		return beforedto;
	}
	
	private String  saveFile(FormFile myFile,Dto inDto,String type)
	{
		try 
		{
			String savePath = getServlet().getServletContext().getRealPath("/") + "file/";
			File file = new File(savePath);
			if (!file.exists()) {
				file.mkdir();
			}
			savePath=savePath+inDto.getAsString("LAND_SN")+"/";
			File file1 = new File(savePath);
			if (!file1.exists()) {
				file1.mkdir();
			}
			//为空时才会只有一个目录！
			if(type!=null)
			{
				savePath=savePath+type+"/";
				File file2=new File(savePath);
				if (!file2.exists()) {
					file2.mkdir();
				}
			}
			String fileName = myFile.getFileName();
			File fileToCreate = new File(savePath+fileName);
			String returnPath=fileToCreate.getPath().substring(fileToCreate.getPath().indexOf(inDto.getAsString("LAND_SN")));
			//如果文件已经存在了就覆盖原来的文件！
			if(returnPath.length()>=70)
			{
					return null;
			}
			else
			{
					FileOutputStream os = new FileOutputStream(fileToCreate);
					os.write(myFile.getFileData());
					os.flush();
					os.close();
					return returnPath.trim();
			}
		} 
		catch (Exception e) 
		{
			System.out.println(e.toString());
			return null;
		}
	}
	//定义一个下载文件的方法
	public ActionForward downloadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		CommonActionForm aForm = (CommonActionForm) form;
		Dto dto = aForm.getParamAsDto(request);
		String field=dto.getAsString("field");
		String dir=getServlet().getServletContext().getRealPath("/")+"file\\";
		if(field!=null)
		{
			System.out.println("要下载的字段是："+field);
			Dto d=(Dto)this.g4Reader.queryForObject("Land.queryPath",dto);
			String path=dir+d.getAsString(field);
			System.out.println("取值："+path);
			//这里文件名必须用工具类处理一下，否则会出现乱码！
			response.setHeader("Content-Disposition", "attachment; filename=" + G4Utils.encodeChineseDownloadFileName(request, path.substring(path.lastIndexOf('\\')+1)) + ";");
			File file = new File(path);
			if(file.exists())
			{
				System.out.println(file.getPath());
				BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));  
		        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);  
		        byte[] temp = new byte[1024];  
		        int size = 0;  
		        while ((size = in.read(temp)) != -1) 
		        {  
		            out.write(temp, 0, size);  
		        }  
		        in.close();
				ServletOutputStream os = response.getOutputStream();
				os.write(out.toByteArray());
				os.flush();
				os.close();
				System.out.println("提示：文件下载成功！");
			}
			else
			{
				this.setErrTipMsg("提示：你要下载的文件不存在！", response);
			}
		}
		else
		{
			System.out.println("当前没有可供下载的资源！");
		}
		return mapping.findForward(null);
	}
	
	
	
	//初始化收支管理页面！
	public ActionForward init2(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		CommonActionForm fForm = (CommonActionForm) form;
		Dto dto = fForm.getParamAsDto(request);
		Dto exist=(Dto)this.g4Reader.queryForObject("Land.existPrj_sn",dto.getAsString("land_sn"));
		//倒换页面时查看当前项目是否已经被删除了
		if(exist==null||exist.getAsString("land_sn")==null)
		{
			request.setAttribute("tip", "提示：对不起，此土地项目被他人已经删除，已经为你刷新了数据...");
			return mapping.findForward("indexView");
		}
		else
		{
			//由于这里的所有操作只针对一个项目，因此可以当前的项目编号存放在会话中进行长会话操作！
			this.setSessionAttribute(request, "land_sn",dto.getAsString("land_sn"));
			
			
			System.out.println("提示：正在转换页面。。。。。。项目编号为："+dto.getAsString("land_sn"));
			//得到根节点菜单的名字！通过菜单的编号，这个编号是唯一的！
			Dto pdto = (Dto)g4Reader.queryForObject("Land.queryAdminName", "010202");
			//将根节点名字保存起来！
			request.setAttribute("rootMenuName", pdto.getAsString("menuname"));
			return mapping.findForward("main");
		}
	}
	
	//加载根节点下的所有子节点！
	public ActionForward queryMenuItems(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		System.out.println("正在加载费用类型下的所有子节点。。。。。。。。。。。。父节点编号是："+request.getParameter("node"));
		//得到当前传递过俩的节点的编号！一定是个节点而不是叶子，否则不会调用这个方法！因此可以断定传来的节点编号一定是个父编号，用于加载他下面的子编号，子编号也有可能是节点！然后再次调用这个方法一直到加载到叶子
		String parentId=request.getParameter("node");
		//注意这里查询的条件，仅仅只有父节点的编号没有其它条件！
		Dto queryChild=new BaseDto();
		queryChild.put("parentid",parentId);
		List list=this.g4Reader.queryForList("Land.queryChildByAdmin",queryChild);
		//什么一个变量用于接收便利出来的记录！
		Dto menuDto =null;
		//对记录进行过滤，将其值变成树菜单可以认识的值！
		for (int i = 0; i < list.size(); i++) 
		{
			menuDto = (BaseDto) list.get(i);
			if (menuDto.getAsString("leaf").equals(ArmConstants.LEAF_Y))
			{
				menuDto.put("leaf", new Boolean(true));
			}
			else
			{
				menuDto.put("leaf", new Boolean(false));
			}
			//只要有2个元素就将其展开！
			if(menuDto.getAsString("id").length()==2)
			{
				menuDto.put("expanded",new Boolean(true));
			}
		}
		//将集合解析成json类型!
		write(JsonHelper.encodeObject2Json(list), response);
		return null;
	}
	
	//创建添加收支的方法
	public synchronized ActionForward saveShouZhi(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		System.out.println("提示：正在添加收支信息。。。。。。。");
		CommonActionForm aForm = (CommonActionForm) form;
		Dto inDto = aForm.getParamAsDto(request);
		//将当前的会话项目id添加到参数中去！
		inDto.put("land_sn",this.getSessionAttribute(request,"land_sn"));
		String time=inDto.getAsString("ldetail_date");
		if(time==null||time.trim().equals(""))
		{
			inDto.put("ldetail_date",new Date());
		}
		else
		{
			inDto.put("ldetail_date",inDto.getAsTimestamp("ldetail_date"));
		}
		System.out.println("=================================="+inDto.getAsString("attc_tp"));
		this.tdxtService.addShouZhi(inDto);
		setOkTipMsg("收支消息添加成功", response);
		return mapping.findForward(null);
	}
	
	//查看当前项目中的所有收支信息！
	public ActionForward shouZhiLook(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		CommonActionForm aForm = (CommonActionForm) form;
		Dto dto = aForm.getParamAsDto(request);
		System.out.println("提示：当前正在查询数据，查询出的数据从"+dto.getAsString("start")+"到"+dto.getAsString("limit"));	
		
		//一旦进入了操作附件的界面那么在session作用域中一定会存在一个名为prj_sn的属性，这个属性在跳转到当前项目附件管理模块时添加进去的，是个长会话！
		dto.put("land_sn",this.getSessionAttribute(request, "land_sn"));
		
		
		String type=dto.getAsString("queryParam");
		if(type!=null&&!type.trim().equals(""))
		{
			if(type.startsWith("支出"))
			{
				dto.put("queryParam","1");
			}
			else
			{
				dto.put("queryParam","0");
			}
		}
		//默认情况加载当前项目编号下的所有附件信息！（仅仅是第一次进入时才是这样），但下次激发这个方法时可能就包含文件名啊，附件类型编号啊，等这些查询信息！
		List list=this.g4Reader.queryForPage("Land.queryShouZhi",dto);
		System.out.println("传递过来的参数有："+dto.toString());
		System.out.println("当前你要项目的id是："+this.getSessionAttribute(request, "land_sn"));
		this.write(JsonHelper.encodeList2PageJson(list, (Integer)this.g4Reader.queryForObject("Land.queryShouZhiCount", dto),null), response);
		return null;
	}
	
	//查看当前项目中的所有附件信息！
	public synchronized ActionForward updateShouZhi(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		System.out.println("提示：正在修改收支信息。。。。。。。");
		CommonActionForm aForm = (CommonActionForm) form;
		Dto inDto = aForm.getParamAsDto(request);
		inDto.put("land_sn",this.getSessionAttribute(request,"land_sn"));
		//处理修改时不填写备注的情况下不会覆盖以前的备注！
		String mark=inDto.getAsString("ldetail_mark");
		if(mark==null||mark.trim().equals(""))
		{
			inDto.put("ldetail_mark"," ");
		}
		inDto.put("ldetail_date",inDto.getAsTimestamp("ldetail_date"));
		this.tdxtService.updateShouZhi(inDto);
		this.setOkTipMsg("修改成功！", response);
		return null;
	}
	//创建删除收支的方法
	public ActionForward deleteShouZhi(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		System.out.println("提示：正在删除收支信息。。。。。。。");
		CommonActionForm aForm = (CommonActionForm) form;
		Dto dto = aForm.getParamAsDto(request);
		String[] strChecked = dto.getAsString("strChecked").split(",");
		Dto delete=new BaseDto();
		//由于所有的删除都是针对同一个项目因此下面这个参数可以在循环外设置
		delete.put("land_sn",this.getSessionAttribute(request, "land_sn"));
		//循环覆盖，虚幻删除！
		for (int i = 0; i < strChecked.length; i++) 
		{
			delete.put("ldetail_sn",strChecked[i]);
			this.tdxtService.deleteShouZhi(delete);
		}
		setOkTipMsg("收支信息删除成功", response);
		return mapping.findForward(null);
	}
}
